"""
用户相关路由
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pydantic import BaseModel, EmailStr, field_validator
from typing import Optional
from datetime import datetime

from backend.app.db.database import get_db
from backend.app.db.operations import user_ops
from backend.app.models.verification import VerificationCode
from backend.app.utils.logger import logger

router = APIRouter(prefix="/user", tags=["用户"])

class UserInfo(BaseModel):
    """用户信息模型"""
    email: str
    password: str
    username: Optional[str] = None

    @field_validator('password')
    def validate_password(cls, v):
        if len(v) < 8:
            raise ValueError('密码长度必须至少为8位')
        return v

class UserResponse(BaseModel):
    """用户响应模型"""
    email: str
    nickname: Optional[str] = None
    avatar: Optional[str] = None
    is_admin: bool = False
    created_at: str

@router.post("/register", response_model=UserResponse)
def register_user(user_info: UserInfo, db: Session = Depends(get_db)):
    """用户注册"""
    try:
        # 检查邮箱是否已存在
        if user_ops.get_user_by_email(db, user_info.email):
            raise HTTPException(
                status_code=400,
                detail="该邮箱已被注册"
            )
        
        # 创建新用户
        user = user_ops.create_user(
            db=db,
            email=user_info.email,
            password=user_info.password,
            username=user_info.username
        )
        
        return {
            "id": user.id,
            "email": user.email,
            "username": user.username,
            "is_active": user.is_active,
            "created_at": user.created_at
        }
        
    except Exception as e:
        logger.error(f"用户注册失败: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"注册失败: {str(e)}"
        )

@router.post("/login")
async def login(
    user_info: UserInfo,
    db: Session = Depends(get_db)
):
    """
    用户登录
    """
    try:
        # 查找用户
        user = user_ops.get_user_by_email(db, user_info.email)
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="邮箱或密码错误"
            )

        # 验证密码
        if not user_ops.verify_password(user_info.password, user.password_hash):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="邮箱或密码错误"
            )

        return {
            "message": "登录成功",
            "user": {
                "id": user.id,
                "email": user.email,
                "username": user.username,
                "is_active": user.is_active
            }
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"登录过程发生错误: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"登录失败: {str(e)}"
        )

@router.get("/me")
async def get_user_info(
    email: EmailStr,
    code: str,
    db: Session = Depends(get_db)
):
    """
    获取用户信息
    """
    # 验证邮箱验证码
    verification_code = db.query(VerificationCode).filter(
        VerificationCode.email == email,
        VerificationCode.code == code,
        VerificationCode.is_used == False,
        VerificationCode.expires_at > datetime.utcnow()
    ).first()
    
    if not verification_code:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="验证码无效或已过期"
        )
    
    # 标记验证码为已使用
    verification_code.is_used = True
    db.commit()
    
    # 获取用户信息
    user = user_ops.get_user_by_email(db, email)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    return {
        "id": user.id,
        "email": user.email,
        "username": user.username,
        "is_active": user.is_active,
        "created_at": user.created_at.isoformat()
    }

@router.put("/me")
async def update_user_info(
    user_info: UserInfo,
    db: Session = Depends(get_db)
):
    """
    更新用户信息
    """
    # 验证邮箱验证码
    verification_code = db.query(VerificationCode).filter(
        VerificationCode.email == user_info.email,
        VerificationCode.code == user_info.verification_code,
        VerificationCode.is_used == False,
        VerificationCode.expires_at > datetime.utcnow()
    ).first()
    
    if not verification_code:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="验证码无效或已过期"
        )
    
    # 标记验证码为已使用
    verification_code.is_used = True
    db.commit()
    
    # 更新用户信息
    updated_user = user_ops.update_user(
        db,
        email=user_info.email,
        nickname=user_info.nickname,
        avatar=user_info.avatar
    )
    
    if not updated_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    return {
        "message": "更新成功",
        "data": {
            "email": updated_user.email,
            "nickname": updated_user.nickname,
            "avatar": updated_user.avatar,
            "is_admin": updated_user.is_admin
        }
    }
